package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理类
 */
@ControllerAdvice(annotations={Controller.class, RestController.class})
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {
    /**
     * 自定义异常处理
     * @param exception
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> customExceptionHandler(CustomException exception){
        log.error("删除分类失败: {}",exception.getMessage());
        return R.error(exception.getMessage());
    }

    /**
     * sql异常处理
     * @param exception
     * @return
     */             //SQLIntegrityConstraintViolationException
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        String message = exception.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String msg = split[2] + "已存在,请重新输入...";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
}
